/* Copyright  2009
   @Author
   Richard Changde Yin            e-mail yinchangde@hotmail.com

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/**
 * @filename: query_arena.h
 */


#ifndef __COLLAPSAR_QUERY_ARENA_H__
#define __COLLAPSAR_QUERY_ARENA_H__

#include <my_alloc.h>

class Item;

class Query_arena
{
public:
  /*
    List of items created in the parser for this query. Every item puts
    itself to the list on creation (see Item::Item() for details))
  */
  Item *free_list;

  MEM_ROOT *mem_root;                   // Pointer to current memroot

  Query_arena(MEM_ROOT *mem_root_arg) :free_list(0), mem_root(mem_root_arg)

  { }
  /*
    This constructor is used only when Query_arena is created as
    backup storage for another instance of Query_arena.
  */
  Query_arena():free_list(0), mem_root(0)
  { }

  virtual ~Query_arena() {};

  inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
  inline void* calloc(size_t size)
  {
    void *ptr;
    if ((ptr=alloc_root(mem_root,size)))
      memset(ptr, 0, size);
    return ptr;
  }
  inline char *strdup(const char *str)
  { return strdup_root(mem_root,str); }
  inline char *strmake(const char *str, size_t size)
  { return strmake_root(mem_root,str,size); }
  inline void *memdup(const void *str, size_t size)
  { return memdup_root(mem_root,str,size); }

  inline void *memdup_w_gap(const void *str, size_t size, uint32_t gap)
  {
    void *ptr;
    if ((ptr= alloc_root(mem_root,size+gap)))
      memcpy(ptr,str,size);
    return ptr;
  }

  void free_items()
  {
    Item *next;
    /* This works because items are allocated with sql_alloc() */
    for (; free_list; free_list= next)
    {
      next= free_list->next;
      free_list->delete_self();
    }
    /* Postcondition: free_list is 0 */
    return;
  }
};


#endif /* __COLLAPSAR_QUERY_ARENA_H__ */
